<?php
/*
	[Phpup.Net!] (C)2009-2011 Phpup.net.
	This is NOT a freeware, use is subject to license terms

	$Id: session.class.php 2010-08-24 10:42 $
*/
if(!defined('IN_BIDCMS')) {
	exit('Access Denied');
}
class controller
{
	private static $models = array();
	private static $hooks = array();
    public function __construct(){
      //控制器初始化
        if(method_exists($this,'init')){
			 $this->init();
    	}
    }
	public function bidcms_model($model_name='',$modelsdir=''){
        if(empty($model_name)){
          return new model();
        }
        if(!empty($modelsdir)){
          $models_dir = $modelsdir;
        } else {
          $models_dir = MODELS_PATH;
        }
		$model_key=str_replace('/','_',$models_dir).'_'.$model_name;
        if (!isset(self::$models[$model_key])){
			$file=$models_dir.'/'.str_replace('_','/',$model_name).'.php';
			if(file_exists($file)) {
				include_once($file);
				$class_name=$model_name.'_class';
				if(!class_exists($class_name)){
					die('Model class_'.$model_name.' Is Lost');
				}
				self::$models[$model_key] = new $class_name();
			} else {
				die('Model file class_'.$model_name.' Is Lost');
			}
		}

		return self::$models[$model_key];
	}
	public function bidcms_template($file = '',$tpldir = '',$stuffix='php') {
      
		$tpl_dir = !empty($tpldir)?$tpldir:VIEWS_PATH.$GLOBALS['controller'];
        $file = !empty($file)?$file:$GLOBALS['action'];
		
        if($stuffix=='html'){
            $tplfile = $tpl_dir.'/'.$file.'.'.$stuffix;
			$comfile =$tpl_dir.'/'.$file.'.tpl.php';
			
			if(!is_file($comfile) || filemtime($tplfile) > filemtime($comfile)) {
				$content = template_parse(file_get_contents($tplfile));
				file_put_contents($comfile,$content);
			}
			return $comfile;
		} else {
			$tplfile = $tpl_dir.'/'.$file.'.'.$stuffix;
			if(!file_exists($tplfile)) {
				exit($file.'文件不存在');
			}
			return $tplfile;
		}
		
	}
	private function bidcms_request($data,$default='',$type='get') {
		global $cookie,$session;
		if($type=='post'){
			if($data){
				return isset($_POST[$data]) && !empty($_POST[$data])?$_POST[$data]:$default;
			}
			return $_POST;
		} elseif($type=='input'){
			$d=file_get_contents('php://input');
			$res=json_decode($d,true);
            if(!$res){
              return $d;
            }
			if($data){
				return isset($res[$data]) && !empty($res[$data])?$res[$data]:$default;
			}
			return $res;
		} elseif($type=='get'){
			if($data){
				return isset($_GET[$data]) && !empty($_GET[$data])?$_GET[$data]:$default;
			}
			return $_GET;
		}
	}
    public function post($val=null,$default=''){
		return $this->bidcms_request($val,$default,'post');
	}
	public function input($val=null,$default=''){
		return $this->bidcms_request($val,$default,'input');
	}
	public function get($val=null,$default=''){
		return $this->bidcms_request($val,$default,'get');
	}
    public function cookie($val=null,$default=''){
        global $cookie;
        $d = '';
        if(!empty($val)){
          $d = $cookie->get($val);
        }
        return !empty($d)?$d:$default;
	}
    public function session($val=null,$default=''){
        global $session;
        $d = '';
        if(!empty($val)){
          $d = $session->get($val);
        }
		return !empty($d)?$d:$default;
	}
	public function bidcms_json($data,$jsonp=false,$callback='') {
		header("content-type:application/json");
		if($jsonp){
			return $callback.'('.json_encode($data).');';
		} else{
			return json_encode($data);
		}
	}
    public function bidcms_success($data=array(),$msg='',$url='',$index = 'code') {
        $res[$index] = 0;
        $res['msg'] = $msg;
        $res['url'] = $url;
        if(!empty($data)){
          if(is_string($data)){
            if(empty($msg)){
              $res['msg'] = $data;
            } else {
              $res['data'] = $data;
            }
          } elseif(is_array($data)){
              $res['data'] = $data;
          }
        }
        echo $this->bidcms_json($res);
        unset($res);
        die();
	}
    public function bidcms_error($data=array(),$msg='',$url='',$index = 'code') {
		$res[$index] = -1;
        $res['msg'] = $msg;
        $res['url'] = $url;
        if(!empty($data)){
          if(is_string($data)){
            if(empty($msg)){
              $res['msg'] = $data;
            } else {
              $res['data'] = $data;
            }
          } elseif(is_array($data)){
              $res['data'] = $data;
          }
        }
        echo $this->bidcms_json($res);
        unset($res);
        die();
	}
	
	//判断表单提交
	public function bidcms_submit_check($submitbutton)
	{
		if(empty($_REQUEST[$submitbutton])) {
			return false;
		} else {
            if(!isset($_SERVER['HTTP_REFERER'])){
              return false;
            }
			$host=preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']);
			if(($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_SERVER['HTTP_X_FLASH_VERSION']) && strpos($_SERVER['HTTP_REFERER'],'demo.bidcms.com')>0)) {
				return true;
			}
			return false;
		}
	}
	//解析页码
	public function bidcms_parse_page($count,$showpage,$example=1)
	{
        $pageinfo='';
        if($count == 0){
          $pageinfo.="<A class='prev' HREF='".$showpage['url']."&page=".($showpage['current_page']>0?$showpage['current_page']-1:0)."'>上一页</A><A class='next' HREF='".$showpage['url']."&page=".($showpage['current_page']+1)."'>下一页<b></b></A>";
          return $pageinfo;
        }
		include_once 'classes/page.class.php';
        $page=new page($count);
		$page->pageSize=$showpage['page_size'];
		$page->setPage();
		$page->pageShowButton=10;
		$page->url=$showpage['url'];
		if($example==0){
			return $page;
		} elseif($example==1) {
			
			if($page->prevPage==0) {
				$pageinfo.="<a class='disabled'>上一页</a>";
			} else {
				$pageinfo.="<A class='prev' HREF='".$page->parseurl($page->prevPage)."'>上一页</A>";
			}
			$button=$page->setFormatPage();
			foreach($button as $key=>$v) {
				if($v==$page->absolutePage+1) {
					$pageinfo.="<a href='javascript:;'>".$v."</a>";
				} else {
					$pageinfo.="<a href='".$page->parseurl($v-1)."' class='not'>".$v."</a>";
				}
			}
			if($page->nextPage<$page->total) {
				$pageinfo.="<A class='next' HREF='".$page->parseurl($page->nextPage)."'>下一页<b></b></A>";
			} else {
				$pageinfo.="<a class='disabled'>下一页</a>";
			}
			return $pageinfo;
		}
		
	}
	//加载hook，返回hook对象，如是不存在返回null;
	public function bidcms_hook($hook,$hooks_dir=''){
		$hooks_dir=!empty($hooks_dir)?$hooks_dir:ROOT_PATH.'plugins';
		if (!isset(self::$hooks[$hook])){
			$file=$hooks_dir.'/'.str_replace('_','/',$hook).'/hook.php';
			if(is_file($file)) {
				include_once($file);
				$class_name=$hook.'_hook';
				if(!class_exists($class_name)){
					die('Hook '.$hook.' Is Lost');
				}
				self::$hooks[$hook] = new $class_name();
			} else {
				die('Hook '.$hook.' Is Lost');
			}
		}

		return self::$hooks[$hook];
	}

	public function bidcms_add_css($file){
		$GLOBALS['css_list'][]=$file;
	}
	public function bidcms_script($data,$function='iframe',$parent=true) {
		$str='<script type="text/javascript">';
		$data=json_encode($data);
		if($parent){
			$str.='parent.'.$function.'('.$data.')';
		} else {
			$str.=$function.'('.$data.')';
		}
		$str.='</script>';
		return $str;
	}
	
}
